import * as React from 'react';
import {observer} from 'mobx-react';
import {message, Icon, Upload, Button, Form} from 'antd';
import {AdBaseFormStore} from '../../AdStore';
import './UploadStyle.less';
declare let GLOBAL;

const FormItem = Form.Item;

@observer
export class UploadItem extends React.Component <{style:any, store:AdBaseFormStore, filedName:string, label:string, labelCol:any, wrapperCol:any }, any > {
  beforeUpload(me) {
      return function(file){
            const isJPG = file.type.match( /^image/ );
            if (!isJPG) {
                message.error('图片格式错误');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片不能超过2M');
            }
            return isJPG && isLt2M;
      }
  }
  handleChange(me){
      return function(info){
          let store:AdBaseFormStore = me.props.store;
          if (info.file.status === 'done') {
              store.valid('imageUrl',info.file.response.url,!store.fields.imageUrl.required);
          }
      }
  }
  render() {
        const {filedName, store, label, labelCol, wrapperCol, style} = this.props;
        const item = store.fields[filedName];

        return (
            <FormItem
                label={label}
                labelCol={labelCol}
                style={style}
                wrapperCol={wrapperCol}
                hasFeedback = {item.hasFeedback}
                required = {item.required}
                help = {item.help}
                validateStatus = {item.validateStatus}>
                <Upload accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp" 
                    className="avatar-uploader" 
                    name="file" 
                    action="/ad-admin/admin/api/file/upload"
                    beforeUpload={this.beforeUpload(this)} 
                    onChange={this.handleChange(this)} 
                    showUploadList={false}>
                        { item.value ?
                        <img src= {`${GLOBAL.imageApiURL}/${item.value}`} alt="" className="avatar" /> :
                        <Icon type="plus" className="avatar-uploader-trigger" /> }
                </Upload>
            </FormItem>
        )
  }
};